package com.yibo.yunpicture.interfaces.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yibo.yunpicture.infrastructure.annotation.AuthCheck;
import com.yibo.yunpicture.interfaces.assembler.SpaceAssembler;
import com.yibo.yunpicture.interfaces.dto.space.*;
import com.yibo.yunpicture.shared.auth.SpaceUserAuthManager;
import com.yibo.yunpicture.infrastructure.common.BaseResponse;
import com.yibo.yunpicture.infrastructure.common.DeleteRequest;
import com.yibo.yunpicture.infrastructure.common.ResultUtils;
import com.yibo.yunpicture.domain.user.constant.UserConstant;
import com.yibo.yunpicture.infrastructure.exception.BusinessException;
import com.yibo.yunpicture.infrastructure.exception.ErrorCode;
import com.yibo.yunpicture.infrastructure.exception.ThrowUtils;
import com.yibo.yunpicture.domain.space.entity.Space;
import com.yibo.yunpicture.domain.user.entity.User;
import com.yibo.yunpicture.domain.space.valueobject.SpaceLevelEnum;
import com.yibo.yunpicture.interfaces.vo.space.SpaceVO;
import com.yibo.yunpicture.application.service.SpaceApplicationService;
import com.yibo.yunpicture.application.service.UserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
@Slf4j
public class SpaceController {

    @Resource
    private SpaceApplicationService spaceApplicationService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 创建空间
     * @param spaceAddDTO
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddDTO spaceAddDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddDTO == null, ErrorCode.PARAMS_ERROR,"请求参数为空");
        User loginUser = userApplicationService.getLoginUser(request);
        Long spaceId = spaceApplicationService.addSpace(spaceAddDTO, loginUser);
        return ResultUtils.success(spaceId);
    }

    /**
     * 删除空间
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userApplicationService.getLoginUser(request);
        long id = deleteRequest.getId();
        //判断空间是否存在
        Space oldSpace = spaceApplicationService.getById(id);
        if (oldSpace == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //仅本人或者管理员能够删除
        spaceApplicationService.checkSpaceAuth(loginUser,oldSpace);
        //删除数据库
        boolean removeById = spaceApplicationService.removeById(id);
        ThrowUtils.throwIf(!removeById, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(removeById);
    }

    /**
     * 更新空间（仅管理员）
     * @param spaceUpdateDTO
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateDTO spaceUpdateDTO) {
        if (spaceUpdateDTO == null || spaceUpdateDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //将实体类和DTO进行类型转换
        Space space = SpaceAssembler.toSpaceEntity(spaceUpdateDTO);
        //自动填充
        spaceApplicationService.fillSpaceBySpaceLevel(space);
        //数据校验
        space.validSpace(false);
        //判断是否存在
        long id = spaceUpdateDTO.getId();
        Space oldSpace = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        //操作数据库
        boolean result = spaceApplicationService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 编辑空间(给用户使用)
     *
     * @param spaceEditDTO
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditDTO spaceEditDTO, HttpServletRequest request) {
        if (spaceEditDTO == null || spaceEditDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和DTO进行转换
        Space space = SpaceAssembler.toSpaceEntity(spaceEditDTO);
        // 设置编辑时间
        space.setEditTime(new Date());
        // 数据校验
        space.validSpace(false);
        // 判断是否存在
        long id = spaceEditDTO.getId();
        Space oldSpace = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        // 仅本人或者管理员能够编辑
        spaceApplicationService.checkSpaceAuth(loginUser,oldSpace);
        //补充审核参数
        spaceApplicationService.fillSpaceBySpaceLevel(space);
        // 操作数据库
        boolean result = spaceApplicationService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回封装类
        return ResultUtils.success(result);
    }

    /**
     * 根据id获取空间
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpace(Long id, HttpServletRequest request) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询数据库
        Space space = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        //获取封装类
        return ResultUtils.success(space);
    }

    /**
     * 根据id获取空间VO
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVO(Long id, HttpServletRequest request) {
        if (id == null || id <= 0) {
            log.info("id + {}", id);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Space space = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceApplicationService.getSpaceVO(space, request);
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(null,space, loginUser);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页查询空间(仅管理员有权限)
     * @param spaceQueryDTO
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryDTO spaceQueryDTO) {
        ThrowUtils.throwIf(spaceQueryDTO == null, ErrorCode.PARAMS_ERROR);
        long current = spaceQueryDTO.getCurrent();
        long pageSize = spaceQueryDTO.getPageSize();
        //查询数据库
        Page page = new Page<>(current, pageSize);
        QueryWrapper<Space> queryWrapper = spaceApplicationService.getQueryWrapper(spaceQueryDTO);
        Page<Space> spacePage = spaceApplicationService.page(page, queryWrapper);
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间封装列表
     * @param spaceQueryDTO
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryDTO spaceQueryDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceQueryDTO == null, ErrorCode.PARAMS_ERROR);
        long current = spaceQueryDTO.getCurrent();
        long pageSize = spaceQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        //查询数据库
        Page page = new Page<>(current, pageSize);
        QueryWrapper<Space> queryWrapper = spaceApplicationService.getQueryWrapper(spaceQueryDTO);
        Page<Space> spacePage = spaceApplicationService.page(page, queryWrapper);
        //获取封装好的空间列表对象
        Page<SpaceVO> spaceVOPage = spaceApplicationService.getSpaceVOPage(spacePage, request);
        return ResultUtils.success(spaceVOPage);
    }

    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceByLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
}
